<template>
  <div class='login'>
      <span class="close">
        <i class="iconicon-test iconfont"></i>
      </span>
      <h2 class='logo'>
        <i class="iconnew iconfont"></i>
      </h2>
      <Myinput 
         v-model="user.username" 
         placeholder="用户名/手机号码"
         :rules='rules.username'
         msg="手机号码不合法"
      ></Myinput>
      <Myinput 
         v-model="user.password" 
         type="passwrod"
         :rules="rules.password"
         placeholder="密码"
         msg="密码不合法"
      ></Myinput>
      <div class="tips"> 
        没有账号？去 <router-link to='/register'>注册</router-link> 
      </div>
      <MyButton @click='btnFn'  type='danger'>登录</MyButton>
      
  </div>
</template>

<script>
import MyButton from "../components/MyButton.vue";
import Myinput from "../components/Myinput.vue";
import {userLoginAPL} from '../apis/user'
import {setToken,setUserId} from '../utils/localData'
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);
export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      rules: {
        username: /^1\d{10}$|^[a-zA-Z]\w{2,10}$|^1\d{4,5}$/,
        password: /^[a-zA-Z0-9~!@#$%^&*()_+=]{3,18}$/,
      },
    };
  },
  components: {
    MyButton,
    Myinput,
  },
  methods: {
    btnFn() {
      // 登录按钮点击时也需要用正则校验
      if (
        this.rules.username.test(this.user.username) &&
        this.rules.password.test(this.user.password)
      ) {
        // 校验通过就发送请求登录
        userLoginAPL({
          // 💥 请求接口参数的键名称，必须按接口文档要求来
          username: this.user.username,
          password: this.user.password,
        }).then((res) => {
          console.log(res);
          const {message}= res.data
           if(message=="登录成功"){
             const {token}=res.data.data
            //  保存到本地存储中
            setToken(token)
            // 把用户 id 存储到本地
            setUserId(res.data.data.user.id)
            //  localStorage.setItem("heima",token)
            //  跳转到个人中心页，并传递id参数
             this.$router.push({path:'/user',query:{id:res.data.data.user.id}})
             this.$toast.success(message);
           }else{
               this.$toast.fail('用户名或密码错误');
           }
        });
      } else {
        // alert("用户名或密码校验失败");
        Toast("用户名或密码校验失败");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.close{
  position: fixed;
  left:20px;
  top:20px;
  .iconfont{
     font-size: 20px;
     color: #ccc;
   }
}
.logo{
   display: flex;
   justify-content: center;
   padding: 80px 0 20px;
   .iconfont{
     font-size: 120px;
     color: #d81e06;
   }
}
.tips{
  font-size:14px;
  padding:0 36px;
  text-align: right;
}
</style>